/*
 * Copyright (C) 2001-2011 Jacek Sieka, arnetheduck on gmail point com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "stdinc.h"
#include "Transfer.h"

#include "UserConnection.h"
#include "ResourceManager.h"
#include "ClientManager.h"
#include "Upload.h"

const string Transfer::names[] =
{
	"file", "file", "list", "tthl"
};

const string Transfer::USER_LIST_NAME = "files.xml";
const string Transfer::USER_LIST_NAME_BZ = "files.xml.bz2";

Transfer::Transfer(UserConnection& conn, const string& path_, const TTHValue& tth_) : segment(0, -1), type(TYPE_FILE), runningAverage(0),
	path(path_), tth(tth_), actual(0), pos(0), userConnection(conn), startPos(0)
{
	start = lastTick = GET_TICK();
}

inline void Transfer::updateRunningAverage(uint64_t tick)
{
	//[!]IRainman refactoring transfer mechanism
	runningAverage = getAverageSpeed();
	lastTick = tick;
}

void Transfer::tick(uint64_t p_CurrentTick)
{
	//[!]IRainman refactoring transfer mechanism
	Lock l(cs);

	if (samples.size() > MIN_SAMPLES)
	{
		const uint64_t ticks = samples.back().first - samples.front().first;
		if (ticks > AVG_PERIOD)
			samples.pop_front();
	}
		
	if (!samples.empty() && samples.back().second == actual)
		samples.back().first = p_CurrentTick;// Position hasn't changed, just update the time
	else
		samples.push_back(Sample(p_CurrentTick, actual));

	updateRunningAverage(p_CurrentTick);
}

int64_t Transfer::getAverageSpeed() const
{
	Lock l(cs);
	if (samples.size() > 2)
	{
		const uint64_t ticks = samples.back().first - samples.front().first;
		const int64_t bytes = samples.back().second - samples.front().second;
		if (ticks > 0)
			return bytes * 1000I64 / ticks;

	}
	// Sample is small (less one or two second), consider the absolute speed in short intervals
	const uint64_t l_smallInterval = (GET_TICK() - start) / 1000I64;
	return getActual() / (l_smallInterval ? l_smallInterval : 1I64);
}

int64_t Transfer::getSecondsLeft(bool wholeFile) const
{
	//[!]IRainman refactoring transfer mechanism
	const int64_t avg = getRunningAverage();
	const int64_t bytesLeft = (wholeFile ? ((Upload*)this)->getFileSize() : getSize()) - getPos();
	return bytesLeft / ((avg > 0) ? avg : 1);
}

void Transfer::getParams(const UserConnection& aSource, StringMap& params) const
{
	const HintedUser& l_User = aSource.getHintedUser();

	params["userCID"] = l_User.user->getCID().toBase32();
	params["userNI"] = Util::toString(ClientManager::getInstance()->getNicks(l_User.user->getCID(), l_User.hint));
	params["userI4"] = aSource.getRemoteIp();
	StringList hubNames = ClientManager::getInstance()->getHubNames(l_User.user->getCID(), l_User.hint);
	if (hubNames.empty())
		hubNames.push_back(STRING(OFFLINE));
	params["hub"] = Util::toString(hubNames);
	StringList hubs = ClientManager::getInstance()->getHubs(l_User.user->getCID(), l_User.hint);
	if (hubs.empty())
		hubs.push_back(STRING(OFFLINE));
	params["hubURL"] = Util::toString(hubs);
	params["fileSI"] = Util::toString(getSize());
	params["fileSIshort"] = Util::formatBytes(getSize());
	params["fileSIchunk"] = Util::toString(getPos());
	params["fileSIchunkshort"] = Util::formatBytes(getPos());
	params["fileSIactual"] = Util::toString(getActual());
	params["fileSIactualshort"] = Util::formatBytes(getActual());
	params["speed"] = Util::formatBytes(getRunningAverage()) + "/" + STRING(S);
	params["time"] = Text::fromT(Util::formatSeconds((lastTick - getStart()) / 1000));//[!]IRainman refactoring transfer mechanism
	params["fileTR"] = getTTH().toBase32();
}
const HintedUser Transfer::getHintedUser() const
{
	return getUserConnection().getHintedUser();
}

//[+]FlylinkDC
UserPtr Transfer::getUser()
{
	return getUserConnection().getUser();
}

const UserPtr Transfer::getUser() const
{
	return getUserConnection().getUser();
}
//[~]FlylinkDC